package com.rick.awarenessdemo

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.media.MediaPlayer
import android.media.RingtoneManager
import android.os.Bundle
import android.os.PowerManager
import android.os.Vibrator
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.amap.api.services.core.PoiItem
import com.rick.awarenessdemo.databinding.DialogRemindBinding
import com.rick.awarenessdemo.util.LogUtil
import java.util.*

/**
 * 提醒弹窗
 */
@SuppressLint("InvalidWakeLockTag")
class RemindDialog : DialogFragment() {

    companion object {
        private const val KEY_POI_ITEM = "KEY_POI_ITEM"

        @JvmStatic
        private var instance: RemindDialog? = null

        @JvmStatic
        fun show(fragmentManager: FragmentManager, poiItem: PoiItem) {
            instance?.dismiss()
            instance = RemindDialog()
            instance?.let {
                it.isCancelable = false
                val bundle = Bundle()
                bundle.putParcelable(KEY_POI_ITEM, poiItem)
                it.arguments = bundle
                it.show(fragmentManager, "")
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        return DataBindingUtil.inflate<DialogRemindBinding>(
            inflater,
            R.layout.dialog_remind,
            null,
            false
        ).root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val binding = DataBindingUtil.getBinding<DialogRemindBinding>(view)
        binding?.let {
            it.text.text = "您即将到达：${arguments?.getParcelable<PoiItem>(KEY_POI_ITEM)?.title}"
            it.btn.setOnClickListener { dismiss() }
        }
        wakeUp()
        startRing()
        startVibrator()
        startTimer()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        stopTimer()
        stopRing()
        stopVibrator()
        releaseWakeLock()
        instance = null
    }

    private var wakeLock: PowerManager.WakeLock? = null

    /**
     * 唤醒屏幕
     */
    private fun wakeUp() {
        val powerManager = context?.getSystemService(Context.POWER_SERVICE) as PowerManager
        wakeLock = powerManager.newWakeLock(
            PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
            "bright"
        )
        wakeLock?.acquire()
    }

    private fun releaseWakeLock() {
        wakeLock?.release()
        wakeLock = null
    }

    private var timer = Timer()

    /**
     * 开启计时器
     */
    private fun startTimer() {
        LogUtil.log("startTimer")
        timer.schedule(object : TimerTask() {
            override fun run() {
                stopTimer()
                stopRing()
                stopVibrator()
                releaseWakeLock()
            }
        }, 45000)
    }

    /**
     * 停止计时器
     */
    private fun stopTimer() {
        LogUtil.log("stopTimer")
        timer.cancel()
    }

    private var mediaPlayer: MediaPlayer? = null

    /**
     * 播放铃声
     */
    private fun startRing() {
        LogUtil.log("startRing")
        context?.let {
            mediaPlayer = MediaPlayer()
            mediaPlayer?.let { mediaPlayer ->
                mediaPlayer.isLooping = true
                mediaPlayer.setDataSource(
                    it,
                    RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
                )
                mediaPlayer.prepare()
                mediaPlayer.start()
            }
        }
    }

    /**
     * 停止铃声
     */
    private fun stopRing() {
        LogUtil.log("stopRing")
        mediaPlayer?.let {
            it.stop()
            it.release()
            mediaPlayer = null
        }
    }

    private val vibrator by lazy {
        context?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    }

    /**
     * 开始震动
     */
    private fun startVibrator() {
        LogUtil.log("startVibrator")
        vibrator.vibrate(
            longArrayOf(2000, 2000),
            0
        )
    }

    /**
     * 停止震动
     */
    private fun stopVibrator() {
        LogUtil.log("stopVibrator")
        vibrator.cancel()
    }
}